package com.chaosyeb.server.controller;

import com.chaosyeb.server.pojo.Admin;
import com.chaosyeb.server.pojo.RespBean;
import com.chaosyeb.server.service.IAdminService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * @Description : 更新个人中心
 * @Author : Chaos
 * @Date : 2022/3/1 16:08
 * @Version : 1.0
 **/
@RestController
public class AdminInfoController {

    @Autowired
    private IAdminService adminService;

    @ApiOperation(value = "更新个人中心")
    @PutMapping("/admin/info")
    public RespBean updateAdmin(@RequestBody Admin admin, Authentication authentication){
        if (adminService.updateById(admin)) {
            //重新设置Authentication
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                    admin, null, admin.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            return RespBean.success("更新成功！");
        }
        return RespBean.error("更新失败！");
    }

    @ApiOperation(value = "更新密码")
    @PutMapping("/admin/pass")
    public RespBean updateAdminPassword(@RequestBody Map<String, Object> info){
        // 获取密码和用户id
        String oldPass = (String) info.get("oldPass");
        String newPass = (String) info.get("newPass");
        Integer adminId = (Integer) info.get("adminId");
        return adminService.updateAdminPassword(oldPass, newPass, adminId);
    }

    @ApiOperation(value = "更新用户头像")
    @PostMapping("/admin/userFace")
    public RespBean updateUserFace(MultipartFile file, Integer id, Authentication authentication){
        return adminService.updateUserFace(file, id, authentication);
    }
}
